// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: GPL-3.0-only

package auth_secret_api_impl

import (
	"context"
	"time"

	"gitcode.com/openseaotter/so_proto_gen_go.git/auth_secret_api"
	"gitcode.com/openseaotter/so_server/config"
	"gitcode.com/openseaotter/so_server/storage"
)

type AuthSecretApiImpl struct {
	auth_secret_api.UnimplementedAuthSecretApiServer
}

func (apiImpl *AuthSecretApiImpl) Add(ctx context.Context, req *auth_secret_api.AddRequest) (*auth_secret_api.AddResponse, error) {
	cfg, err := config.ReadServerConfigFromCache()
	if err != nil {
		return nil, err
	}
	if cfg.SuperToken != "" && req.AccessToken == cfg.SuperToken {
		//do nothing
	} else {
		remoteCfg, ok := cfg.GetRemote(req.RemoteId)
		if !ok {
			return &auth_secret_api.AddResponse{
				Code:   auth_secret_api.AddResponse_CODE_NO_REMOTE,
				ErrMsg: "鉴权服务器不存在",
			}, nil
		}
		_, localMember, err := storage.QueryMember(ctx, remoteCfg.RemoteAddr, req.AccessToken)
		if err != nil {
			return &auth_secret_api.AddResponse{
				Code:   auth_secret_api.AddResponse_CODE_NO_PERMISSION,
				ErrMsg: "用户不存在",
			}, nil
		}
		if !localMember.Perm.ManageAuthSecret {
			return &auth_secret_api.AddResponse{
				Code:   auth_secret_api.AddResponse_CODE_NO_PERMISSION,
				ErrMsg: "没有权限",
			}, nil
		}
	}

	exist, err := storage.AuthSecretDao.Exist(ctx, req.AuthSecret.Username)
	if err != nil {
		return nil, err
	}
	if exist {
		return &auth_secret_api.AddResponse{
			Code:   auth_secret_api.AddResponse_CODE_EXIST_AUTH_SECRET,
			ErrMsg: "验证密钥已存在",
		}, nil
	}

	err = storage.AuthSecretDao.Insert(ctx, req.AuthSecret)
	if err != nil {
		return nil, err
	}

	return &auth_secret_api.AddResponse{
		Code: auth_secret_api.AddResponse_CODE_OK,
	}, nil
}

func (apiImpl *AuthSecretApiImpl) Remove(ctx context.Context, req *auth_secret_api.RemoveRequest) (*auth_secret_api.RemoveResponse, error) {
	cfg, err := config.ReadServerConfigFromCache()
	if err != nil {
		return nil, err
	}
	if cfg.SuperToken != "" && req.AccessToken == cfg.SuperToken {
		//do nothing
	} else {
		remoteCfg, ok := cfg.GetRemote(req.RemoteId)
		if !ok {
			return &auth_secret_api.RemoveResponse{
				Code:   auth_secret_api.RemoveResponse_CODE_NO_REMOTE,
				ErrMsg: "鉴权服务器不存在",
			}, nil
		}
		_, localMember, err := storage.QueryMember(ctx, remoteCfg.RemoteAddr, req.AccessToken)
		if err != nil {
			return &auth_secret_api.RemoveResponse{
				Code:   auth_secret_api.RemoveResponse_CODE_NO_PERMISSION,
				ErrMsg: "用户不存在",
			}, nil
		}
		if !localMember.Perm.ManageAuthSecret {
			return &auth_secret_api.RemoveResponse{
				Code:   auth_secret_api.RemoveResponse_CODE_NO_PERMISSION,
				ErrMsg: "没有权限",
			}, nil
		}
	}

	err = storage.AuthSecretDao.Remove(ctx, req.Username)
	if err != nil {
		return nil, err
	}
	//清除所有ImageGroup里面对应的secretname
	groupInfoList, err := storage.ImageGroupDao.List(ctx)
	if err != nil {
		return nil, err
	}
	for _, groupInfo := range groupInfoList {
		newPullNameList := []string{}
		newPushNameList := []string{}
		for _, secretName := range groupInfo.PermInfo.PullSecretNameList {
			if secretName != req.Username {
				newPullNameList = append(newPullNameList, secretName)
			}
		}
		for _, secretName := range groupInfo.PermInfo.PushSecretNameList {
			if secretName != req.Username {
				newPushNameList = append(newPushNameList, secretName)
			}
		}
		if len(newPullNameList) != len(groupInfo.PermInfo.PullSecretNameList) || len(newPushNameList) != len(groupInfo.PermInfo.PushSecretNameList) {
			groupInfo.PermInfo.PullSecretNameList = newPullNameList
			groupInfo.PermInfo.PushSecretNameList = newPushNameList
			groupInfo.UpdateTime = time.Now().UnixMilli()
			err = storage.ImageGroupDao.Update(ctx, groupInfo)
			if err != nil {
				return nil, err
			}
		}
	}
	return &auth_secret_api.RemoveResponse{
		Code: auth_secret_api.RemoveResponse_CODE_OK,
	}, nil
}

func (apiImpl *AuthSecretApiImpl) Update(ctx context.Context, req *auth_secret_api.UpdateRequest) (*auth_secret_api.UpdateResponse, error) {
	cfg, err := config.ReadServerConfigFromCache()
	if err != nil {
		return nil, err
	}
	if cfg.SuperToken != "" && req.AccessToken == cfg.SuperToken {
		//do nothing
	} else {
		remoteCfg, ok := cfg.GetRemote(req.RemoteId)
		if !ok {
			return &auth_secret_api.UpdateResponse{
				Code:   auth_secret_api.UpdateResponse_CODE_NO_REMOTE,
				ErrMsg: "鉴权服务器不存在",
			}, nil
		}
		_, localMember, err := storage.QueryMember(ctx, remoteCfg.RemoteAddr, req.AccessToken)
		if err != nil {
			return &auth_secret_api.UpdateResponse{
				Code:   auth_secret_api.UpdateResponse_CODE_NO_PERMISSION,
				ErrMsg: "用户不存在",
			}, nil
		}
		if !localMember.Perm.ManageAuthSecret {
			return &auth_secret_api.UpdateResponse{
				Code:   auth_secret_api.UpdateResponse_CODE_NO_PERMISSION,
				ErrMsg: "没有权限",
			}, nil
		}
	}

	exist, err := storage.AuthSecretDao.Exist(ctx, req.AuthSecret.Username)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &auth_secret_api.UpdateResponse{
			Code:   auth_secret_api.UpdateResponse_CODE_NO_AUTH_SECRET,
			ErrMsg: "验证密钥不存在",
		}, nil
	}
	err = storage.AuthSecretDao.Update(ctx, req.AuthSecret)
	if err != nil {
		return nil, err
	}
	return &auth_secret_api.UpdateResponse{
		Code: auth_secret_api.UpdateResponse_CODE_OK,
	}, nil
}

func (apiImpl *AuthSecretApiImpl) Get(ctx context.Context, req *auth_secret_api.GetRequest) (*auth_secret_api.GetResponse, error) {
	emptyInfo := &auth_secret_api.AuthSecretInfo{}

	cfg, err := config.ReadServerConfigFromCache()
	if err != nil {
		return nil, err
	}
	if cfg.SuperToken != "" && req.AccessToken == cfg.SuperToken {
		//do nothing
	} else {
		remoteCfg, ok := cfg.GetRemote(req.RemoteId)
		if !ok {
			return &auth_secret_api.GetResponse{
				Code:       auth_secret_api.GetResponse_CODE_NO_REMOTE,
				ErrMsg:     "鉴权服务器不存在",
				AuthSecret: emptyInfo,
			}, nil
		}
		_, localMember, err := storage.QueryMember(ctx, remoteCfg.RemoteAddr, req.AccessToken)
		if err != nil {
			return &auth_secret_api.GetResponse{
				Code:       auth_secret_api.GetResponse_CODE_NO_PERMISSION,
				ErrMsg:     "用户不存在",
				AuthSecret: emptyInfo,
			}, nil
		}
		if !localMember.Perm.ManageAuthSecret {
			return &auth_secret_api.GetResponse{
				Code:       auth_secret_api.GetResponse_CODE_NO_PERMISSION,
				ErrMsg:     "没有权限",
				AuthSecret: emptyInfo,
			}, nil
		}
	}

	secret, err := storage.AuthSecretDao.Get(ctx, req.Username)
	if err != nil {
		return &auth_secret_api.GetResponse{
			Code:       auth_secret_api.GetResponse_CODE_NO_AUTH_SECRET,
			ErrMsg:     "验证密钥不存在",
			AuthSecret: emptyInfo,
		}, nil
	}

	return &auth_secret_api.GetResponse{
		Code:       auth_secret_api.GetResponse_CODE_OK,
		AuthSecret: secret,
	}, nil
}

func (apiImpl *AuthSecretApiImpl) List(ctx context.Context, req *auth_secret_api.ListRequest) (*auth_secret_api.ListResponse, error) {
	emptyList := []*auth_secret_api.AuthSecretInfo{}

	cfg, err := config.ReadServerConfigFromCache()
	if err != nil {
		return nil, err
	}
	if cfg.SuperToken != "" && req.AccessToken == cfg.SuperToken {
		//do nothing
	} else {
		remoteCfg, ok := cfg.GetRemote(req.RemoteId)
		if !ok {
			return &auth_secret_api.ListResponse{
				Code:           auth_secret_api.ListResponse_CODE_NO_REMOTE,
				ErrMsg:         "鉴权服务器不存在",
				AuthSecretList: emptyList,
			}, nil
		}
		_, localMember, err := storage.QueryMember(ctx, remoteCfg.RemoteAddr, req.AccessToken)
		if err != nil {
			return &auth_secret_api.ListResponse{
				Code:           auth_secret_api.ListResponse_CODE_NO_PERMISSION,
				ErrMsg:         "用户不存在",
				AuthSecretList: emptyList,
			}, nil
		}
		if !localMember.Perm.ManageAuthSecret {
			return &auth_secret_api.ListResponse{
				Code:           auth_secret_api.ListResponse_CODE_NO_PERMISSION,
				ErrMsg:         "没有权限",
				AuthSecretList: emptyList,
			}, nil
		}
	}

	secretList, err := storage.AuthSecretDao.List(ctx)
	if err != nil {
		return nil, err
	}
	return &auth_secret_api.ListResponse{
		Code:           auth_secret_api.ListResponse_CODE_OK,
		AuthSecretList: secretList,
	}, nil
}

func (apiImpl *AuthSecretApiImpl) ListName(ctx context.Context, req *auth_secret_api.ListNameRequest) (*auth_secret_api.ListNameResponse, error) {
	emptyList := []string{}

	cfg, err := config.ReadServerConfigFromCache()
	if err != nil {
		return nil, err
	}
	if cfg.SuperToken != "" && req.AccessToken == cfg.SuperToken {
		//do nothing
	} else {
		remoteCfg, ok := cfg.GetRemote(req.RemoteId)
		if !ok {
			return &auth_secret_api.ListNameResponse{
				Code:     auth_secret_api.ListNameResponse_CODE_NO_REMOTE,
				ErrMsg:   "鉴权服务器不存在",
				NameList: emptyList,
			}, nil
		}
		_, _, err = storage.QueryMember(ctx, remoteCfg.RemoteAddr, req.AccessToken)
		if err != nil {
			return &auth_secret_api.ListNameResponse{
				Code:     auth_secret_api.ListNameResponse_CODE_NO_PERMISSION,
				ErrMsg:   "用户不存在",
				NameList: emptyList,
			}, nil
		}
	}
	secretList, err := storage.AuthSecretDao.List(ctx)
	if err != nil {
		return nil, err
	}

	nameList := []string{}
	for _, secret := range secretList {
		nameList = append(nameList, secret.Username)
	}

	return &auth_secret_api.ListNameResponse{
		Code:     auth_secret_api.ListNameResponse_CODE_OK,
		NameList: nameList,
	}, nil
}
